POJ-3273 Monthly Expense(二分)

描述

传送门:POJ-3273 Monthly Expense

Farmer John is an astounding accounting wizard and has realized he might run out of money to run the farm. He has already calculated and recorded the exact amount of money (1 ≤ moneyi ≤ 10,000) that he will need to spend each day over the next N (1 ≤ N ≤ 100,000) days.

FJ wants to create a budget for a sequential set of exactly M (1 ≤ M ≤ N) fiscal periods called “fajomonths”. Each of these fajomonths contains a set of 1 or more consecutive days. Every day is contained in exactly one fajomonth.

FJ’s goal is to arrange the fajomonths so as to minimize the expenses of the fajomonth with the highest spending and thus determine his monthly spending limit.

输入描述

Line 1: Two space-separated integers: N and M
Lines 2.. N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day

输出描述

Line 1: The smallest possible monthly limit Farmer John can afford to live with.

示例

输入

1
2
3
4
5
6
7
8
7 5
100
400
300
100
500
101
400

输出

1
500

Hint

If Farmer John schedules the months so that the first two days are a month, the third and fourth are a month, and the last three are their own months, he spends at most $500 in any month. Any other method of scheduling gives a larger minimum monthly limit.

题解

题目大意

分期:将N个账款分割成M个财务期,使得每个分期账款和的最大值最小。
给出农夫在n天中每天的花费,要求把这n天分作m组,每组的天数必然是连续的,要求分得各组的花费之和应该尽可能地小,最后输出各组花费之和中的最大值。

思路

最大值最小的问题,可以采用二分来解决,二分其中一个值,算另一个结果,找到上届或下届。
在这个题中 二分组的最大花费,计算是不是可以分为m组,找出最小的花费。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <queue>
const int MAXN = 1e5 +10;
const int INF = 0x3f3f3f3f;
using namespace std;
int n, m;
int a[MAXN];

bool Judge(int mid){
int cnt = 0;
for(int i = 0; i < n;){
if(mid < a[i]) return false;
int sum = 0;
bool f = true;
while(sum+a[i] <= mid){
sum += a[i++];
f = false;
}
if(f){
i++;
}
cnt++;
}
if(cnt > m) return false;
else return true;
}

int main(){
scanf("%d %d", &n, &m);
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
int l = 1, r = INF;
while(l < r){
int mid = (l+r) >>1;
if(Judge(mid)){
r = mid;
}
else{
l = mid+1;
}
}
printf("%d", l);
}


/*
5 5
100
200
300
400
500

*/